package com.sky.common.interceptors;

import cn.hutool.core.util.StrUtil;
import com.sky.common.context.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 员工信息传递： 网关 -> 微服务
 * 员工信息拦截器,因为通过网关过滤器之后，微服务需要员工信息，故编写此拦截器，从请求头中获取员工信息，再存入ThreadLocal
 * @author toki
 */
@Slf4j
public class AdminInfoInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从请求头中获取员工信息
        final String adminInfo = request.getHeader("admin-info");
        // 判断员工信息是否为空
        if (StrUtil.isNotBlank(adminInfo)){
            // 只要有，存入ThreadLocal
            BaseContext.setCurrentId(Long.valueOf(adminInfo));
        }
//        log.info("获取到员工信息：{}", adminInfo);
        // 只放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 清理员工信息
        BaseContext.removeCurrentId();
    }
}
